import 'package:flutter/material.dart';

/**
 * 帮助我们访问某个Widget的信息
 */
class GlobalKeyDmeo extends StatelessWidget {
  final GlobalKey<_ChildPageState> _globalKey = GlobalKey();

  GlobalKeyDmeo({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('GlobalKeyDemo'),
        centerTitle: true,
      ),
      body: ChildPage(key: _globalKey),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          _globalKey.currentState?.setState(() {
            _globalKey.currentState!.data =
                'old:' + _globalKey.currentState!.count.toString();
            _globalKey.currentState!.count++;
          });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}

class ChildPage extends StatefulWidget {
  const ChildPage({super.key});

  @override
  State<ChildPage> createState() => _ChildPageState();
}

class _ChildPageState extends State<ChildPage> {
  int count = 0;
  String data = 'hello';

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        children: [
          Text(count.toString()),
          Text(data),
        ],
      ),
    );
  }
}
